package com.aishang.javacv.lab.executor;

import com.aishang.javacv.lab.dao.VideoAddrDao;
import com.aishang.javacv.lab.entity.VideoAddr;
import com.aishang.javacv.lab.jobs.VideoPusher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;

@Slf4j
@Service
public class VideoPushExecutor {

    @Resource
    private Executor executor;

    @Resource
    private VideoAddrDao videoAddrDao;

    @Resource
    private ConcurrentLinkedQueue<VideoPusher> pusherQueue;

    @Value("${fanyue.video-location-prefix}")
    private String videoLocationPrefix;

    /**
     * 开启全部设备
     * @return
     */
    public String start() {
        List<VideoAddr> list = videoAddrDao.getList();
        log.info("开启列表：{}",list);
        log.info("target前缀：{videoLocationPrefix}",list);
        list.forEach(videoAddr -> start(videoAddr));
        return "ok";
    }


    /**
     * 开启指定设备
     * @param videoAddr
     * @return
     */
    public String start(VideoAddr videoAddr) {
        String pushLocation = videoLocationPrefix + videoAddr.getTarget();
        log.info("开启：{}",videoAddr.toString());
        log.info("拉流地址：{}", videoAddr.getSource());
        log.info("推流地址：{}", pushLocation);
        VideoPusher pusher = new VideoPusher(videoAddr.getSource(), pushLocation, false);
        pusherQueue.add(pusher);
        executor.execute(pusher);
        return "ok";
    }

    /**
     * 停止全部设备
     * @param from
     * @return
     */
    public String stop(String from) {
        if(StringUtils.isEmpty(from)){
            while (!pusherQueue.isEmpty()){
                VideoPusher pusher = pusherQueue.poll();
                pusher.setExit(true);
            }
        }
        return "ok";
    }

    /**
     * 重启全部设备
     */
    public void restart() {
        this.stop(null);
        this.start();
    }

    /**
     * 添加配置并开启
     * @param videoAddr
     * @return
     */
    public String addAndStart(VideoAddr videoAddr) {
        videoAddrDao.insert(videoAddr);
        start(videoAddr);
        return "ok";
    }

    public String add(VideoAddr videoAddr) {
        videoAddrDao.insert(videoAddr);
        return "ok";
    }

    public List<VideoAddr> getList() {
        return videoAddrDao.getList();
    }

    public String update(VideoAddr videoAddr) {
        videoAddrDao.update(videoAddr);
        return "ok";
    }

    public List<VideoAddr> delete(Long id) {
        VideoAddr videoAddr = videoAddrDao.selectById(id);
        videoAddr.setDeleteFlag("1");
        videoAddrDao.update(videoAddr);
        return videoAddrDao.getList();
    }
}
